﻿using UnityEngine;
using System.Collections;

public class lockedDoorScript :MonoBehaviour  {
	
	bool activated;
	public Renderer myLock;
	public plankDropScript[] planks;
	int phase;
	public Texture2D keyOnHoleTex;
	public Transform stepOn;
	public AudioClip openSound;
	
	// Use this for initialization
	void Start () {
		//myLock = this.transform;
	}
	
	// Update is called once per frame
	void Update () {
	
		if(activated)
		{
			if(phase == 0)
			{
				Color tmpCol = myLock.material.color;
				tmpCol.a -= Time.deltaTime * 1.5f;
				myLock.material.color = tmpCol;
				
				if(myLock.material.color.a <= 0)	
				{
					phase = 1;
				}
			}
			else if(phase == 1)
			{
				bool allFinished = true;
				for(int i = 0 ; i < 7; i++)
				{
					if(!planks[i].finishDropping)
						allFinished = false;
					
					if(planks[i].dropTiming < 0)
						continue;
					
					planks[i].dropTiming -= Time.deltaTime;
					if(planks[i].dropTiming < 0)
						planks[i].dropPlankTo(transform.position.y - 1.65f);

				}
				if(allFinished)
				{
					phase = 2;
					this.collider.enabled = false;
					Destroy(stepOn.gameObject);
				}
			}
		}
	}
	
	void OnCollisionEnter(Collision myCol)
	{
		playerScript player;
		if(player = myCol.gameObject.GetComponent<playerScript>())
		{
			if(player.isCarryKey)
			{
				player.unlockDoor();
				audio.PlayOneShot(openSound);
				RPC_Activated();
				networkView.RPC("RPC_Activated",RPCMode.Others);
			}
		}
	}
	
	[RPC]
	void RPC_Activated()
	{
		myLock.material.mainTexture = keyOnHoleTex;
		activated = true;
		phase = 0;
	}
}
